import {
  Inject,
  Controller,
  Get,
  Post,
  Body,
  Query,
  Param,
  Req,
  ValidationPipe,
  Logger,
  Version,
} from '@nestjs/common';
import { Cache, CACHE_MANAGER } from '@nestjs/cache-manager';
import { Request } from 'express';
import { UserService } from './user.service';
import { ResponseInterface } from '../common/response/response.interface';
import { SuccessResponse } from '../common/response/success-response';
import { ErrorResponse } from '../common/response/error-response';
import {
  SaveUserDataResponse,
  UserListResponse,
} from './response/user-response';

import { SaveUserDto, DelUserDto } from './dto/user.dto';

// @Controller({
//     path: 'user',
//     version: '1',
// }) // 变成了/v1/user
@Controller('user')
export class UserController {
  constructor(
    @Inject(CACHE_MANAGER)
    private cacheManager: Cache,
    private readonly userService: UserService,
  ) {} // 注入服务层

  @Get('index/:id/:cid') // 如 /user/index/123/456
  index(@Param() params): string {
    return `this is simon's home. id=${params.id}, cid=${params.cid}`;
  }

  @Get('profile/:id') // 即 /user/profile => getUserProfile()
  getUserProfile(@Req() request: Request): string {
    return 'yyy';
  }

  @Get('yyy') // 如 /user/yyy?name=simon
  getDetail(@Query() query): string {
    console.log('query===', query);
    return 'yyy';
  }

  // 缓存使用示例
  @Get('set/cache') // 如 /user/set/cache
  async setUserCache(@Query() query): Promise<void> {
    const value = await this.cacheManager.get('myname');
    if (!value || value == '') {
      await this.cacheManager.set('myname', 'simon');
      // await this.cacheManager.set('myname', 'simon', 1000); // TTL(过期时间，以秒为单位)
      // await this.cacheManager.set('myname', 'simon', 0); // 0为不过期
      // 删除指定缓存
      // await this.cacheManager.del('myname');
      // 清空整个缓存
      // await this.cacheManager.reset();
    }
  }

  @Get('hobby')
  // @Version('1') // 对某个api单独加版本控制，变成了/v1/user/hobby，不影响其他api
  async getHobby(): Promise<any[]> {
    // 支持异步方法
    return ['编程', '书法', 'K歌'];
  }

  @Get('list') // 如 /user/list?limit=10&offset=0
  async getUserList(@Query() query): Promise<ResponseInterface> {
    try {
      // offset = (page - 1) * limit
      const [userListResponse, total] = await this.userService.getUserList(
        query.address,
        query.age,
        query.limit,
        query.offset,
      );
      return new SuccessResponse(userListResponse, total);
    } catch (e: any) {
      return new ErrorResponse(e.message);
    }
  }

  @Get('detail/:id') // 如 /user/detail/123
  async getUserDetail(@Param() params): Promise<ResponseInterface> {
    try {
      const userResponse = await this.userService.getUserDetail(params.id);
      return new SuccessResponse(userResponse);
    } catch (e: any) {
      return new ErrorResponse(e.message);
    }
  }

  @Post('save') // 如 /user/save
  async saveUser(
    @Body(new ValidationPipe()) dto: SaveUserDto,
  ): Promise<ResponseInterface> {
    // 引入ValidationPipe，自动验证表单参数
    try {
      const userResponse: SaveUserDataResponse =
        await this.userService.saveUser(dto);
      return new SuccessResponse(userResponse);
    } catch (e: any) {
      return new ErrorResponse(e.message);
    }
  }

  @Post('del') // 如 /user/del
  async delUserDetail(
    @Body(new ValidationPipe()) dto: DelUserDto,
  ): Promise<ResponseInterface> {
    try {
      await this.userService.delUser(dto.id, dto.address);
      return new SuccessResponse({ id: dto.id });
    } catch (e: any) {
      return new ErrorResponse(e.message);
    }
  }
}
